# coding: utf-8
import queue

from host.settings import ALERT_TEMPLATE_BODY, \
    ALERT_TEMPLATE_HEADER, \
    ALERT_TEMPLATE_REC_BODY, \
    ALERT_TEMPLATE_REC_HEADER
from util.log import logger

# 告警异常计数表
ALERT_COMPUTE_TABLE = dict()
# 告警信息待发表
ALERT_TABLE = queue.Queue(maxsize=1000)


def host_alert(ip, value):
    err_count = ALERT_COMPUTE_TABLE.get(ip, 0)
    if value == 'success':
        # 移除异常历史
        ALERT_COMPUTE_TABLE.pop(ip, None)
        # 发送恢复告警
        if err_count != 0:
            alert_msg_header = '异常恢复:主机%s恢复' % ip
            alert_msg_body = '异常恢复:主机%s恢复' % ip
            ALERT_TABLE.put((alert_msg_header, alert_msg_body))
            logger.info('生成恢复信息:%s,%s' % (ip, alert_msg_header))
    else:
        err_count += 1
        if err_count == 1:
            alert_msg_header = '异常告警:主机%s不可达,%s' % (ip, value)
            alert_msg_body = '异常告警:主机%s不可达,%s' % (ip, value)
            ALERT_TABLE.put((alert_msg_header, alert_msg_body))
            logger.info('生成告警信息:%s,%s' % (ip, alert_msg_header))

        ALERT_COMPUTE_TABLE[ip] = err_count


def compute_alert(ip, gather_type, name, value, threshold, op, trigger):
    """
    告警策略计算
    :param ip:
    :param gather_type:
    :param name:
    :param value:
    :param threshold:
    :param op:
    :param trigger:
    :return: None
    """

    # 告警计数键
    key = '%s_%s_%s' % (ip, gather_type, name)

    # 取异常计数
    err_count = ALERT_COMPUTE_TABLE.get(key, 0)

    # 若本次状态正常，弹出之前不良记录，同时如果发过告警则发恢复告警
    # 若本次状态异常，进入告警判定流程
    if value < threshold:
        # 移除异常历史
        ALERT_COMPUTE_TABLE.pop(key, None)
        # 发送恢复通知
        if err_count >= trigger:
            # 消息标题
            alert_msg_header = ALERT_TEMPLATE_REC_HEADER % (ip, gather_type, name, value, threshold)
            # 消息内容
            alert_msg_body = ALERT_TEMPLATE_REC_BODY % (ip, gather_type, name, value, threshold)
            # 放入告警队列
            ALERT_TABLE.put((alert_msg_header, alert_msg_body))
            logger.info('生成恢复信息:%s,%s' % (ip, alert_msg_header))

    else:
        # 增加异常计数
        err_count += 1
        # 触发告警发送
        if err_count == trigger:
            # 消息标题
            alert_msg_header = ALERT_TEMPLATE_HEADER % (ip, gather_type, name, value, threshold, err_count)
            # 消息内容
            alert_msg_body = ALERT_TEMPLATE_BODY % (ip, gather_type, name, value, threshold, err_count)
            # 放入发送队列
            ALERT_TABLE.put((alert_msg_header, alert_msg_body))
            logger.info('生成告警信息:%s,%s' % (ip, alert_msg_header))

        # 更新异常计数
        ALERT_COMPUTE_TABLE[key] = err_count
